/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package moon;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;

/**
 *
 * @author Moon
 */
public class MyServer {

    IServer server;

    public MyServer() {
        try {
            server = new Server(1234, new MyHandler());
        } catch (UnknownHostException ex) {
            Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void start() {
        try {
            server.start();
        } catch (IOException ex) {
            Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    class MyHandler implements IDataHandler, IConnectHandler, IDisconnectHandler {

        public boolean onData(INonBlockingConnection inbc) throws IOException,
                BufferUnderflowException,
                ClosedChannelException,
                MaxReadSizeExceededException {
            String data = inbc.readStringByDelimiter("|");
            System.out.println(data);
            return true;
        }

        public boolean onConnect(INonBlockingConnection inbc) throws IOException,
                BufferUnderflowException,
                MaxReadSizeExceededException {
            String remoteName = inbc.getRemoteAddress().getHostName();
            System.out.println(remoteName + " has connected!");
            return true;
        }

        public boolean onDisconnect(INonBlockingConnection inbc) throws IOException {
            String remoteName = inbc.getRemoteAddress().getHostAddress();
            int remotePort = inbc.getRemotePort();
            System.out.println(remoteName + ":" + remotePort);
            return true;
        }
    }

    public static void main(String[] args) {
        MyServer srv = new MyServer();
        srv.start();
    }
}